package request

import (
	"bytes"
	"encoding/json"
	"fmt"
	"gitee.com/jn-qq/go-tools/data"
	"io"
	"maps"
	"net/http"
	"strings"
)

type T5 struct {
	txt        string
	sense      string
	intention  string
	resultData map[string]any
}

func (t *T5) Reset() {
	t.txt = ""
	t.sense = ""
	t.intention = ""
	clear(t.resultData)
}

func (t *T5) NewTaskData(row map[string]any) error {
	// 复制数据
	t.resultData = maps.Clone(row)
	if txt, ok := row["问题"]; ok {
		t.txt = strings.TrimSpace(txt.(string))
		if strings.HasPrefix(t.txt, "客户：") {
			t.txt = "客户：" + t.txt
		}
	} else {
		t.resultData["备注"] = "参数错误"
		return fmt.Errorf("参数错误")
	}
	if sense, ok := row["场景"]; ok {
		t.sense = strings.TrimSpace(sense.(string))
	}
	return nil
}

func (t *T5) Do() {
	// 构建请求参数
	payload := map[string]any{
		"inputs": fmt.Sprintf("基于客户与坐席的对话历史，综合判断客户最后一句话所属的意图和槽位。\n###对话历史开始###\n%s\n###对话历史结束###\n客户最后一句话所属的意图与槽位是：", t.txt),
		"parameters": map[string]any{
			"max_new_tokens": 100,
		},
	}
	// 请求参数序列化
	body, err := json.Marshal(payload)
	if err != nil {
		t.resultData["备注"] = "参数错误：" + err.Error()
		return
	}
	t.resultData["请求参数"] = string(body)
	// 发送post请求
	response, err := http.Post("http://115.190.27.75:19004/generate", "application/json", bytes.NewReader(body))
	if err != nil {
		t.resultData["备注"] = "请求异常：" + err.Error()
		return
	}
	defer response.Body.Close()
	// 响应断言
	if response.StatusCode != http.StatusOK {
		t.resultData["备注"] = "请求异常,响应状态码：" + response.Status
		return
	}
	// 响应数据解析
	jsonData, err := io.ReadAll(response.Body)
	if err != nil {
		t.resultData["备注"] = "读取响应异常：" + err.Error()
	}
	var resp map[string]string
	if err := json.Unmarshal(jsonData, &resp); err != nil {
		t.resultData["备注"] = "响应解析异常：" + err.Error()
	}
	// 结果解析
	generatedText := resp["generated_text"]
	t.resultData["结果"] = generatedText
	var intent []map[string]any
	if err := json.Unmarshal([]byte(generatedText), &intent); err != nil {
		t.resultData["备注"] = "结果解析异常：" + err.Error()
	} else {
		if len(intent) > 0 {
			for k := range intent[0] {
				t.resultData["意图"] = k
				t.intention = k
				break
			}
		}
	}
}

func (t *T5) Result() map[string]any {
	// 简单断言
	if t.sense != "" {
		info := t.resultData["备注"].(string) + "\n" + data.TernaryExpression(t.sense == t.intention, "TRUE", "FALSE")
		t.resultData["备注"] = strings.TrimSpace(info)
	}
	return maps.Clone(t.resultData)
}
